package com.me.app;

import java.util.HashMap;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import com.me.db.CalendarManager;
import com.me.db.CalendarQuery;
import com.me.util.AppConstant;
import com.me.util.AppUtil;
//import com.me.util.MeParser;

public class WelcomeActivity extends Activity {

	CalendarManager calendarManager;
	SharedPreferences sharedPref;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_welcome);

		init();

		// new Handler().postDelayed(new Runnable() {
		// @Override
		// public void run() {
		//
		// init();
		// }
		// }, AppConstant.SPLASH_TIME_OUT);

	}

	private void init() {

		calendarManager = new CalendarManager(getContentResolver());

		// fetch the share preferences
		sharedPref = PreferenceManager
				.getDefaultSharedPreferences(getApplicationContext());
		String currCalendarId = sharedPref.getString(
				AppConstant.CURRENT_CALENDAR_ID, null);
		String currCalendarName = sharedPref.getString(
				AppConstant.CURRENT_CALENDAR_NAME, null);

		AppUtil.App.currButtonSize = sharedPref.getString(
				AppConstant.CURRENT_BUTTON_SIZE,
				AppConstant.DEFAULT_BUTTON_SIZE);

		AppUtil.App.defaultEventType = sharedPref.getString(
				AppConstant.DEFAULT_EVENT_TYPE, AppConstant.EVENT_PENDING);

		// no share preferences for the first time login
		if (currCalendarId == null || currCalendarName == null) {

			// query the android calendar
			Cursor cursor = calendarManager.fetchCalendar();
			int count = cursor.getCount();

			if (count <= 0) {
				Toast.makeText(getBaseContext(), AppConstant.TOAST_NO_ACCOUNT,
						Toast.LENGTH_SHORT).show();

				new Handler().postDelayed(new Runnable() {

					@Override
					public void run() {

						// System.exit(0);
						proceedWithWelcome();
					}
				}, AppConstant.SPLASH_TIME_OUT);

			} else {

				HashMap<String, String> accountList = new HashMap<String, String>();
				;

				// retrieve the result from cursor
				while (cursor.moveToNext()) {
					accountList
							.put(String.valueOf(cursor
									.getInt(CalendarQuery.Calendar.INDEX_ID)),
									cursor.getString(CalendarQuery.Calendar.INDEX_ACCOUNT_NAME));
				}

				// pop up dialog for user to select google account
				Dialog dialog = buildDialog(accountList);
				dialog.setCanceledOnTouchOutside(false);
				dialog.setOnDismissListener(new OnDismissListener() {

					@Override
					public void onDismiss(DialogInterface dialog) {
						if (AppUtil.App.currCalendarId == null
								|| AppUtil.App.currCalendarName == null
								|| AppUtil.App.currCalendarName.length() <= 0) {
							Toast.makeText(getBaseContext(),
									AppConstant.TOAST_NO_ACCOUNT_SELECTION,
									Toast.LENGTH_SHORT).show();

							new Handler().postDelayed(new Runnable() {

								@Override
								public void run() {
									System.exit(0);
								}
							}, AppConstant.SPLASH_TIME_OUT);
						}
					}
				});
				dialog.show();

			}

		} else {
			AppUtil.App.currCalendarId = currCalendarId;
			AppUtil.App.currCalendarName = currCalendarName;
			
			proceedWithWelcome();
			
			// proceed();
//
//			// start main activity
//			startActivity(new Intent(WelcomeActivity.this, HomeActivity.class));
//			// close this activity
//			finish();
		}
	}

	private Dialog buildDialog(HashMap<String, String> accountList) {

		int size = accountList.size();
		final String[] accountIDs = accountList.keySet().toArray(
				new String[size]);
		final String[] accountNames = accountList.values().toArray(
				new String[size]);

		String title = AppConstant.DIALOG_TITLE_SELECT_CALENDAR;

		AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);

		dialogBuilder.setTitle(title).setItems(accountNames,
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {

						AppUtil.App.currCalendarId = accountIDs[which];
						AppUtil.App.currCalendarName = accountNames[which];

						// save the retrieved calendar id and calendar name
						SharedPreferences.Editor editor = sharedPref.edit();
						editor.putString(AppConstant.CURRENT_CALENDAR_ID,
								AppUtil.App.currCalendarId);
						editor.putString(AppConstant.CURRENT_CALENDAR_NAME,
								AppUtil.App.currCalendarName);
						editor.commit();

						proceedWithWelcome();
					}
				});

		return dialogBuilder.create();
	}

	private void proceedWithWelcome() {

		//AppUtil.App.meParser = new MeParser();
		new Handler().postDelayed(new Runnable() {
			@Override
			public void run() {

				// start main activity
				startActivity(new Intent(WelcomeActivity.this,
						HomeActivity.class));
				// close this activity
				finish();
			}
		}, AppConstant.SPLASH_TIME_OUT);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.welcome, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
}
